var express = require('express');
var tag_router = express.Router();
var db = require('../../models');
const sequelize = require('sequelize');
const Op = require('sequelize').Op;
var comm = require('../../comm')


/**
 * @author: Shihh
 * @description: 分页获取标签列表
 * @param {type} 
 * @return:   
 */
tag_router.post('/getTags', async (req, res) => {
  var searchData = req.body.searchData
  var [page = 1, pagesize = 30] = [req.body.pageSet.pageNo, req.body.pageSet.pageSize]
  let condition = {
    "pagesize": pagesize,
    "page": page
  }
  let where = {}
  if (searchData.name) {
    where['name'] = {
      [Op.like]: `%${searchData.name}%`
    }
  }
  if (searchData.group) {
    where['group'] = searchData.group
  }
  condition.where=where
  let tags = await db.tag.getTagList(condition)
  
  let data = {
    code: 200,
    rows: tags.rows,
    count:tags.count
  }
  res.json(data)
});

/**
 * 获取所有标签(去重)  可删除
 */

tag_router.get('/getTagsList', async (req, res) => {
  let tags = await db.tag.findAll()
  res.json(tags)
});

/**
 * 根据tag ID 获取tag名称
 */
tag_router.get('/getTagName', async (req, res) => {
  let queryData = { id: req.query.tag_id }
  let tag = await db.tag.getOneTag(queryData)
  res.json(tag)
});

/**
 * @author: Shihh
 * @description: 获取标签总数
 * @param {type} 
 * @return: 
 */

tag_router.get('/tagCount', async (req, res) => {
  let tagCount = await db.tag.getTagCount()
  res.json(tagCount)
});

/**
 * @author: Shihh
 * @description: 修改标签 判断标签名是否重复
 * 页面条件
 * @param {type} 
 * @return: 
 */
tag_router.post('/editTag', async (req, res) => {
  let result = {
    code: "",
    msg: "",
  }
  let bool = await db.tag.updateTag(req.body)
  console.log(bool)
  if (bool) {
    result.code = "200"
    result.msg = "修改成功"
  } else {
    result.code = "201"
    result.msg = "已存在标签，请更换标签名"
  }

  res.json(result)

});


/**
 * @author: Shihh
 * @description: 新增标签
 * @param {type} 
 * @return: 
 */
tag_router.post('/saveTag', async (req, res) => {
  let result = {
    code: "",
    msg: "",
  }
  let re = await db.tag.findOrCreate({
    where: { name: req.body.name },
    defaults: { group: req.body.group, remark: req.body.remark, group_name: req.body.group_name }
  }).then(([tag, bool]) => {
    comm.redis.set(tag.id, req.body.name, function () { })
    return bool
  })
  if (re) {
    result.code = "200"
    result.msg = "添加成功"
    res.json(result)
  } else {
    result.code = "201"
    result.msg = "已存在标签，请勿重复添加"
    res.json(result)
  }
});


/**
 * @author: Shihh
 * @description: 批量设置标签分组  update
 * @param {type} 
 * @return: 
 */
tag_router.post('/batchTagsGroup', async (req, res) => {
  let modifyIds = req.body.tagIds
  let groupInfo = req.body.groupInfo
  let result = await db.tag.update(
    { group: groupInfo.group, group_name: groupInfo.group_name },
    {
      where: {
        "id": {
          [Op.in]: modifyIds
        },
      }
    })
  res.json(result)
});

/**
 * @author: Shihh
 * @description: 批量删除标签  并删除图片tagIds下的标签
 * 1. 获取所有使用标签的imageId
 * 2. 删除标签与图片的关系
 * 3. 获取所有图片的tagIds
 * 4. 更新图片表的tagIds字段
 * @param {type} 
 * @return: 
 */
tag_router.post('/batchTagsDel', async (req, res) => {
  let delIds = req.body
  let imgIds = await db.tagImage.findAll(
    {
      attributes: [
        sequelize.fn('distinct', sequelize.col('image_id'))
      ],
      where: {
        "tag_id": {
          [Op.in]: delIds
        },
      },
      group: 'image_id',
      raw: true
    }
  )
  let imgArr = []
  imgIds.forEach(item => {
    imgArr.push(item.image_id)
  })
  //删除标签与图片的关系
  let result = await db.sequelize.transaction(t => {
    return db.tagImage.destroy(
      {
        where: {
          "tag_id": {
            [Op.in]: delIds
          },
        },
        transaction: t
      },
    ).then(tag => {
      return db.tag.destroy(
        {
          where: {
            "id": {
              [Op.in]: delIds
            },
          },
          transaction: t
        },
      ).then(tags => {
        return db.tagImage.findAll({
          attributes: [
            ['image_id', 'id'],
            [sequelize.fn('group_concat', sequelize.col('tag_id')), 'tagIds']
          ],
          raw: true,
          where: {
            'image_id': {
              [Op.in]: imgArr
            }
          },
          group: 'image_id',
          transaction: t
        }).then(imgs => {
          return db.images.bulkCreate(
            imgs,
            {
              updateOnDuplicate: ["id", 'tagIds'],
              transaction: t
            },
          ).then(() => {
            delIds.forEach(item => {
              comm.redis.del(item)
            })
            return true
          })
        })
      })
    });
  }).then(result => {
    return result
  }).catch(err => {
    return false
  })
  res.json(result)
});


/**
 * @author: Shihh
 * @description: 根据ID或name查询标签
 * @param {type} ？？？？
 * @return: 
 */
tag_router.post('/getTagByIdOrName', async (req, res) => {
  //按照name查询tag
  let param = req.body.queryString
  let querydata = await db.tag.findAll({ where: { [Op.or]: [{ name: { [Op.like]: `%${param}%` } }, { id: param }] } })
  res.json(querydata)
})



/**
 * @author: Shihh
 * @description: 批量添加tag与image关系
 * @param {type} 
 * @return: 
 */
tag_router.post('/batchAddTags', async (req, res) => {
  let tagIds = req.body.tagIds
  let imgIds = req.body.imgIds
  let insertArr = []
  for (let item of tagIds) {
    let tagName = await db.tag.findByPk(item)
    imgIds.forEach(imgId => {
      insertArr.push({ tag_id: item, tag_name: tagName.name, image_id: imgId })
    })
  }
  await db.sequelize.transaction(t => {
    var promises = []
    insertArr.forEach(async item => {
      var result = await db.tagImage.findCreateFind({
        where: { tag_id: item.tag_id, image_id: item.image_id },
        defaults: { tag_id: item.tag_id, image_id: item.image_id, tag_name: item.tag_name },
        transaction: t
      })
      promises.push(result)
    });
    return Promise.all(promises).then(async () => {
      return await db.tagImage.findAll({
        attributes: [
          ['image_id', 'id'],
          [sequelize.fn('group_concat', sequelize.col('tag_id')), 'tagIds']
        ],
        raw: true,
        where: {
          'image_id': {
            [Op.in]: imgIds
          }
        },
        group: 'image_id',
        transaction: t
      }).then(imgs => {
        return db.images.bulkCreate(
          imgs,
          {
            updateOnDuplicate: ["id", 'tagIds'],
            transaction: t
          },
        ).then(() => {
          return true
        })
      })
    })
  }).then(re => {
    res.json('操作成功')
  }).catch(err => {
    res.json('操作失败')
  })
});


module.exports = tag_router
